import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[nsLoading]'
})
export class LoadingDirective implements OnChanges {
  @Input() nsLoading: boolean = false;
  @Input() nsLoadingText: string = '加载中...';
  @Input() nsLoadingBakColor: string = 'rgba(255, 255, 255, 0.4)';

  private loadingElement: HTMLElement | null = null;

  constructor(private elementRef: ElementRef) {
    // 移除强制设置 position: relative
    // this.elementRef.nativeElement.style.position = 'relative';
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['nsLoading']) {
      if (this.nsLoading) {
        this.createLoadingElement();
      } else {
        this.removeLoadingElement();
      }
    }
  }

  private createLoadingElement() {
    if (this.loadingElement) return;

    // 检查父元素的定位属性
    const parentPosition = window.getComputedStyle(this.elementRef.nativeElement).position;
    if (parentPosition === 'static') {
      this.elementRef.nativeElement.style.position = 'relative';
    }

    this.loadingElement = document.createElement('div');
    this.loadingElement.className = 'ns-loading-overlay';

    const styles = {
      'position': 'absolute',
      'top': '0',
      'left': '0',
      'right': '0',
      'bottom': '0',
      'background-color': this.nsLoadingBakColor,
      'display': 'flex',
      'flex-direction': 'column',
      'justify-content': 'center',
      'align-items': 'center',
      'z-index': '1000'
    };

    Object.entries(styles).forEach(([key, value]) => {
      this.loadingElement!.style[key as any] = value;
    });

    const spinner = document.createElement('div');
    spinner.className = 'ns-loading-spinner';
    spinner.style.width = '25px';
    spinner.style.height = '25px';
    spinner.style.border = '3px solid #f3f3f3';
    spinner.style.borderTop = '4px solid #3498db';
    spinner.style.borderRadius = '50%';
    spinner.style.animation = 'spin 1.5s linear infinite';

    const styleSheet = document.createElement('style');
    styleSheet.textContent = `
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `;
    document.head.appendChild(styleSheet);

    const textElement = document.createElement('div');
    textElement.className = 'ns-loading-text';
    textElement.textContent = this.nsLoadingText;
    textElement.style.marginTop = '10px';
    textElement.style.color = '#3498db';
    textElement.style.fontSize = '14px';

    this.loadingElement.appendChild(spinner);
    this.loadingElement.appendChild(textElement);
    this.elementRef.nativeElement.appendChild(this.loadingElement);
  }

  private removeLoadingElement() {
    if (this.loadingElement) {
      this.elementRef.nativeElement.removeChild(this.loadingElement);
      this.loadingElement = null;
    }
  }
}